package com.hdd.fmh.module.sys.utils;

import com.hdd.fmh.common.context.SpringContextHolder;
import com.hdd.fmh.common.redis.RedisMapper;
import com.hdd.fmh.common.utils.JsonUtils;
import com.hdd.fmh.common.utils.StringUtils;
import com.hdd.fmh.module.sys.bean.User;
import com.hdd.fmh.module.sys.mapper.UserMapper;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class UserUtils {
    //根据 token 获取用户信息
    private static RedisMapper redisMapper = SpringContextHolder.getBean(RedisMapper.class);

    private static UserMapper userMapper = SpringContextHolder.getBean(UserMapper.class);


    public static User getUserByToken() throws Exception {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        if(StringUtils.isNullOrEmpty(request.getHeader("token"))) {
           throw  new Exception("获取用户失败");
        }
        String token = request.getHeader("token");
        String userStr =redisMapper.get(token);//

        User  user = JsonUtils.readValue(userStr, User.class);
        // 为了数据同步 获取id  根据id 查询用户数据库信息
        user = userMapper.selectByPrimaryKey(user.getId());
        return  user;
    }

    public static Integer getUserIdByToken() throws Exception {
        User  user =  getUserByToken();
        return  user.getId();
    }

}
